package com.example.hbuildble

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updateLayoutParams
import com.example.hbuildble.databinding.ActivityMainBinding
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.longtxt.powerband.PbManager
import com.longtxt.powerband.core.BleDevice
import com.longtxt.powerband.models.BaseResponse
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    private lateinit var bleAdapter: BleDeviceAdapter

    private lateinit var alertDialog: AlertDialog


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(binding.toolbar)
        initUI()
        copyFileFromAssetsToInternalStorage("watch6.bin", "test/watch6.bin")
        copyFileFromAssetsToInternalStorage("rabbit_360.bin", "test/rabbit_360.bin")
        copyFileFromAssetsToInternalStorage("screen_360_2.png", "test/screen_360_2.png")
        copyFileFromAssetsToInternalStorage("update.ufw", "test/update.ufw")
    }

    private fun initUI() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.toolbar) { v, windowInsets ->
            val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.updateLayoutParams<ViewGroup.MarginLayoutParams> {
                topMargin = insets.top
            }
            WindowInsetsCompat.CONSUMED
        }
        alertDialog = AlertDialog.Builder(this,R.style.FullScreenDialogTheme).setView(R.layout.dialog_loading).create()
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.llMain)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        PbManager.initScanner(this){
            Log.i(TAG, "initUI: $it")
        }
        binding.btnPermission.setOnClickListener {
            checkBlePermission()
        }
        binding.btnScan.setOnClickListener {
            showLoadingDialog()
            PbManager.startScan(10) { list ->
                val typeT = object : TypeToken<BaseResponse<List<BleDevice>>>() {}.type
                val bleResp = Gson().fromJson<BaseResponse<List<BleDevice>>>(
                    list,
                   typeT
                )
//                binding.tvStatus.text = "Scan finished,$bleResp"
                bleAdapter.setDataList(bleResp.data!!)
                dismissLoadingDialog()
            }
        }
        binding.btnCallJl.setOnClickListener {
            //PbManager.callJL()
            startActivity(Intent(this, TestingActivity::class.java))
        }
        bleAdapter = BleDeviceAdapter{
           handleBleConnection(it.mac)
        }
        binding.rvDevice.adapter = bleAdapter
    }

    private fun handleBleConnection(macStr: String) {
        showLoadingDialog()
        PbManager.connectByMac(this,macStr){
            if (!PbManager.isInOta) {
                dismissLoadingDialog()
                val response = Gson().fromJson<BaseResponse<String>>(it, BaseResponse::class.java)
                if (response.code == 1) {
                    startActivity(Intent(this, TestingActivity::class.java))
                } else {
                    PbManager.disconnect {  }
                    Toast.makeText(this, response.message, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun checkBlePermission() {
        var result =
            checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) + checkSelfPermission(
                Manifest.permission.ACCESS_FINE_LOCATION
            )
        result += if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S) {
            checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) + checkSelfPermission(
                Manifest.permission.BLUETOOTH_CONNECT
            )
        } else {
            0
        }
        if (result != PackageManager.PERMISSION_GRANTED) {
            var permissionsList = mutableListOf(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION

            )
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S) {
                permissionsList.addAll(
                    listOf(
                        android.Manifest.permission.BLUETOOTH_SCAN,
                        android.Manifest.permission.BLUETOOTH_CONNECT
                    )
                )
            }
            requestPermissions(permissionsList.toTypedArray(), 10086)
        } else {
            Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.sum() == PackageManager.PERMISSION_GRANTED) {
            if (requestCode == 10086) {
                Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show()
            }
        }
    }

    companion object {
        private const val TAG = "MainActivity"

    }

    private fun showLoadingDialog() {
        if (!alertDialog.isShowing) {
            alertDialog.show()
        }
    }

    private fun dismissLoadingDialog() {
        if (alertDialog.isShowing) {
            alertDialog.dismiss()
        }
    }


    fun copyFileFromAssetsToInternalStorage(assetFileName: String, destFileName: String) {
        val assetManager = assets
        val fileDir = filesDir
        val outFile = File(fileDir, destFileName)
        val outDir = outFile.parentFile

        // 如果目标目录不存在，则创建它
        if (outDir != null && !outDir.exists()) {
            if (!outDir.mkdirs()) {
                // 创建目录失败时处理逻辑
                println("Failed to create directory: ${outDir.absolutePath}")
                return
            }
        }

        if (!outFile.exists()) {
            try {
                assetManager.open(assetFileName).use { inputStream ->
                    FileOutputStream(outFile).use { outputStream ->
                        inputStream.copyTo(outputStream)
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        val filePath = outFile.absolutePath
        println("Image path: $filePath")
    }
}